package com.effectivsocial.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import lombok.extern.slf4j.Slf4j;

import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.effectivsocial.domain.Link;
import com.effectivsocial.domain.LinkGroup;
import com.effectivsocial.repository.LinkGroupRepository;
import com.effectivsocial.repository.LinkRepository;
import com.effectivsocial.service.api.AbstractService;
import com.effectivsocial.service.api.LinkGroupService;

@Named
@Transactional(readOnly = true)
@Slf4j
public class LinkGroupServiceImpl extends AbstractService<LinkGroup, String>
		implements LinkGroupService {
	@Inject
	private LinkGroupRepository repository;
	
	@Inject
	private LinkRepository linkRepository;

	@Override
	protected void initInternal() {
		setRepository(repository);
	}

	public List<LinkGroup> findAll() {
		return repository.findAll();
	}

	public LinkGroup findByName(String name) {
		return repository.findByName(name);
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void appendLink(String linkGroupName, String link) {
		
		
		Link loadedLink = linkRepository.findOne(link);
		
		
		LinkGroup linkGroup = repository.findByName(linkGroupName);
		List<Link> existing = linkGroup.getLinks();
		
		if(existing == null) {
			List<Link> links = new ArrayList<Link>();
			links.add(loadedLink);
			linkGroup.setLinks(links);
		}
		else{
			existing.add(loadedLink);
		}
		
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	public void deleteAllAssociatedLinks() {
		List<LinkGroup> linkGroups = repository.findAll();
		
		for(LinkGroup linkGroup : linkGroups) {
			linkGroup.setLinks(null);
		}
		
	}
}
